<template>
    <div class="home">
        <div class="box">
            <div class="box-text-1">你好 !</div>
            <div class="box-text-2">{{ titleText }}</div>

            <el-form 
                v-if="showType == 'login'"
                ref="ruleFormRef1"
                :model="formData1" 
                :rules="rules1"
                label-width="auto"
                status-icon
            >
                <el-form-item 
                    label=""
                    label-width="0"
                    prop="username"
                >
                    <el-input 
                        v-model="formData1.username" 
                        :prefix-icon="User"
                        size="large"
                        clearable
                        placeholder="请输入账号"
                        @keyup.enter="onSubmit1(ruleFormRef1)"
                    />
                </el-form-item>
                <el-form-item 
                    label=""
                    label-width="0"
                    prop="password"

                >
                    <el-input 
                        v-model="formData1.password" 
                        :prefix-icon="Lock"
                        size="large"
                        type="password"
                        show-password
                        clearable
                        placeholder="请输入密码"
                        @keyup.enter="onSubmit1(ruleFormRef1)"
                    />
                </el-form-item>
                <el-form-item 
                    label=""
                    label-width="0"
                    prop="captcha"
                >
                    <el-input 
                        v-model="formData1.captcha" 
                        :prefix-icon="Monitor"
                        size="large"
                        clearable
                        placeholder="请输入验证码"
                        class="code_box"
                        @keyup.enter="onSubmit1(ruleFormRef1)"
                    >
                        <template #append>
                            <div 
                                class="code_num"
                                @click="getCode"
                                readonly
                            >
                                {{code}}
                            </div>
                        </template>
                    </el-input>
                    
                </el-form-item>
                <el-form-item
                    label-width="0"
                >
                    <el-button 
                        type="primary" 
                        @click="onSubmit1(ruleFormRef1)"
                    >
                        登录
                    </el-button>
                </el-form-item>
                <div class="login-text-box">
                    <!-- <div 
                        class="login-text"
                        @click="showType = 'register'; titleText = '注册'"
                    >
                        注册
                    </div> -->
                    <!-- <div 
                        class="login-text"
                        @click="showType = 'modify'; titleText = '修改密码'"
                    >
                        修改密码
                    </div>
                    <div 
                        class="login-text"
                        @click="showType = 'forget'; titleText = '忘记密码'"
                    >
                        忘记密码
                    </div> -->
                </div>
                
            </el-form>
            <el-form 
                v-else-if="showType == 'register'"
                ref="ruleFormRef2"
                :model="formData2" 
                :rules="rules2"
                label-width="auto"
                status-icon
            >
                <el-form-item 
                    label=""
                    label-width="0"
                    prop="username"
                >
                    <el-input 
                        v-model="formData2.username" 
                        :prefix-icon="User"
                        size="large"
                        clearable
                        placeholder="请输入账号"
                        @keyup.enter="onSubmit2(ruleFormRef2)"
                    />
                </el-form-item>
                <el-form-item 
                    label=""
                    label-width="0"
                    prop="phone"
                >
                    <el-input 
                        v-model="formData2.phone" 
                        :prefix-icon="Phone"
                        size="large"
                        clearable
                        maxlength="11"
                        placeholder="请输入手机号"
                        @keyup.enter="onSubmit2(ruleFormRef2)"
                    >
                        <template #append>
                            <el-button 
                                type="primary" 
                                :disabled="phoneCaptchaText != '获取验证码'"
                                @click="getPhoneCaptcha"
                            >
                                {{ phoneCaptchaText }}
                            </el-button>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item 
                    label=""
                    label-width="0"
                    prop="captcha"
                >
                    <el-input 
                        v-model="formData2.captcha" 
                        :prefix-icon="Monitor"
                        size="large"
                        clearable
                        placeholder="请输入验证码"
                        @keyup.enter="onSubmit2(ruleFormRef2)"
                    />
                </el-form-item>
                <el-form-item 
                    label=""
                    label-width="0"
                    prop="password"

                >
                    <el-input 
                        v-model="formData2.password" 
                        :prefix-icon="Lock"
                        size="large"
                        clearable
                        type="password"
                        show-password
                        placeholder="请输入密码"
                        @keyup.enter="onSubmit2(ruleFormRef2)"
                    />
                </el-form-item>
                <el-form-item
                    label-width="0"
                >
                    <el-button 
                        type="primary" 
                        @click="onSubmit2(ruleFormRef2)"
                    >
                        注册
                    </el-button>
                </el-form-item>
                <div class="login-text-box">
                    <div 
                        class="login-text"
                        @click="showType = 'login'; titleText = '登录'"
                    >
                        登录
                    </div>
                    <!-- <div 
                        class="login-text"
                        @click="showType = 'modify'; titleText = '修改密码'"
                    >
                        修改密码
                    </div>
                    <div 
                        class="login-text"
                        @click="showType = 'forget'; titleText = '忘记密码'"
                    >
                        忘记密码
                    </div> -->
                </div>
                
            </el-form>
        </div>
        
    </div>
</template>

<script lang="ts" setup>
    import { ref, reactive, markRaw, onBeforeMount, onMounted, onBeforeUnmount, nextTick, computed  } from 'vue'
    import type { Ref, Raw } from 'vue'
    import { doLoginApi } from '@/apis'
    import { isPhone, deepClone } from '@/utils'

    import { useRoute, useRouter } from 'vue-router'
    import { storeToRefs } from 'pinia'
    import { useStore } from '@/store'
    import { ElMessage, ElLoading } from 'element-plus'

    import {
        Lock,
        User,
        Monitor,
        Phone,
    } from '@element-plus/icons-vue'
    import md5 from 'js-md5'
    

    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    const { isLocked } = storeToRefs(store)
	const avatarImage = new URL('@/assets/img/avatar/avatar.png', import.meta.url).href
    // const avatarImage: Raw<any[]> = markRaw([new URL('@/assets/img/avatar/avatar.png', import.meta.url).href])
    const titleText: Ref<string> = ref('欢迎来到泰州儿童系统！')
    const showType = ref<string>('login') //register, modify, forget
    const phoneCaptchaText = ref<string>('获取验证码')
    
    const code: Ref<string> = ref('') //声明一个变量用于存储生成的验证码
    onMounted(() => {
        getCode()
    })
    // 随机验证码生成
    const getCode = () => {
        let arrays = new Array(
            '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
            'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
            'u', 'v', 'w', 'x', 'y', 'z',
        );
        // 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
        //   'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
        //   'U', 'V', 'W', 'X', 'Y', 'Z'
        code.value = ''; //重新初始化验证码
        //随机从数组中获取四个元素组成验证码
        for (var i = 0; i < 4; i++) {
            //随机获取一个数组的下标
            let r: number = parseInt((Math.random() * arrays.length).toString())
            code.value += arrays[r];
        }
        code.value; //将验证码写入指定区域
    }
    
    const ruleFormRef1 = ref<any>()
    const ruleFormRef2 = ref<any>()
    const formData1: Ref<any> = ref({
        username: '', //3212
        password: '', //Tzmz!@#2021
        captcha: '',
    })
    const formData2: Ref<any> = ref({
        username: '',
        password: '',
        captcha: '',
        phone: '',
    })
    const rules1 = reactive<any>({
        username: [
            { 
                required: true, 
                message: '请输入账号！', 
                trigger: 'blur' 
            },
        ],
        password: [
            { 
                required: true, 
                message: '请输入密码！', 
                trigger: 'blur' 
            },
        ],
        captcha: [
            { 
                required: true, 
                message: '请输入验证码！', 
                trigger: 'blur' 
            },
            { 
                validator: (rule: any, value: any, callback: any) => {
                    if (value == code.value) {
                        callback()
                    } else {
                        getCode()
                        callback(new Error('请输入正确的验证码！'))
                    }
                },
                trigger: 'blur' 
            },
        ],
    })
    const rules2 = reactive<any>({
        username: [
            { 
                required: true, 
                message: '请输入账号！', 
                trigger: 'blur' 
            },
        ],
        password: [
            { 
                required: true, 
                message: '请输入密码！', 
                trigger: 'blur' 
            },
        ],
        captcha: [
            { 
                required: true, 
                message: '请输入验证码！', 
                trigger: 'blur' 
            },
        ],
        phone: [
            { 
                required: true, 
                message: '请输入手机号！', 
                trigger: 'blur' 
            },
            { 
                validator: (rule: any, value: any, callback: any) => {
                    if (isPhone(value)) {
                        callback()
                    } else {
                        callback(new Error('请输入正确的手机号！'))
                    }
                },
                trigger: 'blur' 
            },
        ],
    })
    const onSubmit1 = (formEl: any) => {
        if (!formEl) return;
        formEl.validate(async (valid, fields) => {
            console.log(valid)
            console.log(fields)
            if (valid) {
                console.log('submit!')
                // let data = JSON.parse(JSON.stringify(formData1.value))
                let data = deepClone(formData1.value)

                data.password = md5(data.password)

                try {
                    let res: any = await doLoginApi(data)
                    store.openid = '1' //正常应该后台反过来
                    store.nickName = res.data.name 
                    if (route.query.redirect) {
                        router.replace(route.query.redirect as string)
                    } else {
                        router.replace('/')
                    }
                } catch (error) {
                    getCode()
                } finally {

                }
                
            } else {
                console.log('error submit!')
                ElMessage({
                    message: fields[Object.keys(fields)[0]][0].message,
                    type: 'warning',
                })
            }
        })
    }
    const onSubmit2 = (formEl: any) => {
        if (!formEl) return;
        formEl.validate((valid, fields) => {
            console.log(valid)
            console.log(fields)
            if (valid) {
                console.log('submit!')
                store.openid = '1'
                if (route.query.redirect) {
                    router.replace(route.query.redirect as string)
                } else {
                    router.replace('/')
                }
            } else {
                console.log('error submit!')
                ElMessage({
                    message: fields[Object.keys(fields)[0]][0].message,
                    type: 'warning',
                })
            }
        })
    }
    const getPhoneCaptcha = () => {
        let num = 60
        phoneCaptchaText.value = num + 's'
        let interval = setInterval(() => {
            phoneCaptchaText.value = --num + 's'
            if (num <= 0) {
                phoneCaptchaText.value = '获取验证码'
                clearInterval(interval)
            }
        }, 1000)
        // 调接口
    }
    
</script>

<style lang="scss" scoped>
    // .home::after {
    //     content: '';
    //     position: absolute;
    //     left: 0;
    //     top: 0;
    //     z-index: -1;
    //     width: 100vw;
    //     height: 100vh;
    //     background-image: url('@/assets/avatar/bg8.png');
    //     background-size: 100% 100%;
    //     filter: blur(5px);
    // }
    .home {
        width: 100vw;
        height: 100vh;
        overflow: hidden;
        background: url('@/assets/img/bg/bg-2.png');
        background-size: 100% 100%;
        background-color: #fff;
    }
    .box {
        background-color: rgba(255, 255, 255, 0.1);
        width: 550px;
        height: 500px;
        box-sizing: border-box;
        padding: 40px;
        border-radius: 10px;
        position: absolute;
        right: 200px;
        top: 200px;
        color: #fff;
        text-align: left;
        .box-text-1 {
            font-size: 40px;
            font-weight: bold;
            padding: 10px 0;
        }
        .box-text-2 {
            font-size: 26px;
            padding: 10px 0;

        }
        .login-text-box {
            display: flex;
            .login-text {
                margin: 10px;
                color: #577aff;
                cursor: pointer;
            }
        }
        
    }
    .code_box {
        .el-input-group__append {
            display: initial;
        }
        .code_num {
            width: 100px;
            height: 100%;
            // background-color: rgb(197, 214, 228);
            font-size: 18px;
            text-align: center;
            letter-spacing: 5px;
            cursor: pointer;
        }
    }
    
</style>